<template>
  <el-dialog
    title="打印设置"
    :visible="visible"
    v-loading="loading"
    width="88%"
    :append-to-body="true"
    @open="handleOpen"
    @close="close"
    :fullscreen="true"
  >
    <el-form
      :model="form"
      ref="form"
      label-width="60px"
      :inline="false"
      size="small"
    >
      <el-row :gutter="20">
        <el-col :span="5" :offset="0">
          <el-form-item label="最小值:">
            <el-input v-model="form.min" placeholder="请输入"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="5" :offset="0">
          <el-form-item label="最大值:">
            <el-input v-model="form.max" placeholder="请输入"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="4" :offset="0">
          <el-button type="primary" size="small" @click="renderEchart"
            >生成图表</el-button
          >
        </el-col>
      </el-row>
    </el-form>

    <div id="taskChart" style="width: 100%;height: auto;" :key="key">
      <!-- A4纸大小 height: 210mm;width: 297mm; -->
      <div
        style="page-break-after:always"
        v-for="(item, index) in echartsList"
        :key="index"
        :style="{
          height: chartHeight,
          width: chartWidth
        }"
        class="chart"
        :ref="'chart' + index"
      ></div>
    </div>
    <!-- v-newPrint="print" -->
    <span slot="footer">
      <el-button type="primary" size="small" @click="printChart"
        >打 印</el-button
      >
      <button style="display:none" v-newPrint="print" ref="printBtn">
        打印
      </button>
      <!-- <el-button type="primary" size="small" @click="printChart"
        >打 印</el-button
      > -->
      <el-button size="small" @click="close">取 消</el-button>
    </span>
  </el-dialog>
</template>

<script>
let that = null;
import { mapGetters } from "vuex";
import print from "vue-print-nb";
import { renderTestArr } from "./test";
import { generateId } from "@/utils";
export default {
  directives: {
    newPrint: print
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      key: 1,
      form: {
        min: "300",
        max: "820"
      },
      loading: false,
      chartHeight: "700px",
      chartWidth: "100%",
      lineChart: null,
      echartsList: [],
      print: {
        id: "taskChart", //这里的id就是上面我们的打印区域id，实现指哪打哪
        popTitle: "", // 打印配置页上方的标题
        extraHead: "", // 最上方的头部文字，附加在head标签上的额外标签，使用逗号分割
        preview: false, // 是否启动预览模式，默认是false
        previewTitle: "预览的标题", // 打印预览的标题
        previewPrintBtnLabel: "预览结束，开始打印", // 打印预览的标题下方的按钮文本，点击可进入打印
        zIndex: 20002, // 预览窗口的z-index，默认是20002，最好比默认值更高
        importCss: true,
        importStyle: true,
        printDelay: 500,
        honorMarginPadding: true,
        landscape: false,
        grayscale: false,
        previewBeforeOpenCallback() {
          console.log("正在加载预览窗口！");
        }, // 预览窗口打开之前的callback
        previewOpenCallback() {
          console.log("已经加载完预览窗口，预览打开了！");
        }, // 预览窗口打开时的callback
        beforeOpenCallback() {
          console.log("开始打印之前！");
        }, // 开始打印之前的callback
        openCallback() {
          console.log("执行打印了！");
        }, // 调用打印时的callback
        closeCallback() {
          that.loading = false;
          console.log("关闭了打印工具！");
        }, // 关闭打印的callback(无法区分确认or取消)
        clickMounted() {
          that.chartHeight = "700";
          that.chartWidth = "100%";
          setTimeout(() => {
            that.resizeChart();
          }, 1000);
          console.log("点击v-print绑定的按钮了！", that.chartHeight);
        }
      }
    };
  },

  computed: {},
  created() {
    that = this;
  },
  mounted() {
    const ARR = renderTestArr(300);
    const ARR2 = renderTestArr(400);
    // this.echartsList = [
    //   {
    //     lineChart: null,
    //     data: [
    //       {
    //         list: ARR,
    //         color: "#eb2100"
    //       },
    //       {
    //         list: ARR2,

    //         color: "#d0a00e"
    //       }
    //     ]
    //   }
    // ];

    this.echartsList = {
      lineChart: null,
      data: [
        {
          list: ARR,
          color: "#eb2100"
        },
        {
          list: ARR2,
          color: "#d0a00e"
        }
      ]
    };
    let arr = [];
    let arr2 = [];
    this.echartsList.data.map(item => {
      const list = (this.echartsList = this.renderList(item.list));
      arr.push(list);
    });

    const l = arr[0].length;
    for (let index = 0; index < l; index++) {
      arr2.push({
        lineChart: null,
        data: arr.map(item => {
          return item[index];
        })
      });
    }
    console.log("arr :>> ", arr2);

    this.init();
    window.addEventListener("resize", this.resizeChart);
  },
  methods: {
    renderList(data) {
      // 将时间字符串转换为 moment 对象
      // const arr = data.data;

      let groups = [[]]; // 初始化为一个空数组
      // 第一个温区
      const obj1 = data;
      // const obj2 = arr[1].list;
      let start = obj1[0][0]; // 开始时间为第一条时间

      for (let i = 0; i < obj1.length; i++) {
        const time = this.$moment(obj1[i][0], "YYYY-MM-DD HH:mm:ss");
        const diff = this.$moment.duration(time.diff(start)).asHours(); // 计算当前时间与开始时间的小时差

        if (diff >= 10) {
          // 如果小时差大于等于10，创建一个新组
          groups.push([obj1[i]]);
          start = time; // 将开始时间更新为当前时间
        } else {
          // 否则将时间加入到当前组中
          groups[groups.length - 1].push(obj1[i]);
        }
      }

      // const list = groups.map(item => {
      //   return {
      //     lineChart: null,
      //     data: [
      //       {
      //         list: item,
      //         color: "#eb2100"
      //       }
      //     ]
      //   };
      // });
      return groups;
    },
    renderEchart() {
      this.key = generateId();
      this.init();
    },
    printChart() {
      this.loading = true;
      that.chartHeight = "210mm";
      that.chartWidth = "297mm";
      setTimeout(() => {
        this.resizeChart();
        setTimeout(() => {
          this.$refs.printBtn.click();
        }, 500);
      }, 500);
    },
    resizeChart() {
      this.echartsList.forEach(item => {
        if (item.lineChart) {
          item.lineChart.resize();
        }
      });
    },
    disposeChart() {
      this.echartsList.forEach(item => {
        if (item.lineChart) {
          item.lineChart.dispose();
          item.lineChart = null;
        }
      });
    },
    init() {
      this.disposeChart();
      let gmax = Number(this.form.max);
      let gmin = Number(this.form.min);
      this.$nextTick(() => {
        this.echartsList.forEach((echart, echartIndex) => {
          echart.lineChart = this.$echarts.init(
            this.$refs[`chart${echartIndex}`][0],
            null,
            {
              renderer: "svg"
            }
          );
          let series = [];
          echart.data.forEach((chart, chartIndex) => {
            const dashedLine = [];
            const list = chart.list.map((item, index) => {
              const num = ((item[1] - gmin) / ((gmax - gmin) / 100)) % 100;
              return [item[0], num, item[1]];
            });
            let flg = 0;
            let v1 = gmax;
            let v2 = gmin;
            list.forEach((item, index) => {
              let flg1 = parseInt((item[2] - gmin) / (gmax - gmin));
              if (flg1 > flg) {
                if (flg != 0) {
                  v1 += gmax - gmin;
                  v2 += gmax - gmin;
                }
                const value1 = flg == 0 ? gmax : v1;
                const value2 = flg == 0 ? gmin : v2;
                list.splice(index, 0, [item[0], "--", item[2]]);
                dashedLine.push({
                  name: "测量温度",
                  type: "line",
                  data: [
                    [item[0], 0],
                    [item[0], 100]
                  ],
                  itemStyle: {
                    normal: {
                      color: chart.color,
                      lineStyle: {
                        width: 2,
                        type: "dotted" //'dotted'虚线 'solid'实线
                      }
                    }
                  },
                  markPoint: {
                    symbolSize: [20, 20],
                    // 设置偏移量
                    symbolOffset: [0, 0],
                    data: [
                      {
                        // symbol:
                        //   "path://M13.811,7h3.918L10.874,0,4.021,7H8.036c0,5-1.568,8.5-4.993,11C7.937,17,12.833,14,13.811,7Z",
                        coord: [item[0], 100],
                        value: `${value1}℃`,
                        label: {
                          position: "top",
                          color: chart.color
                        },
                        itemStyle: {
                          color: chart.color
                        }
                      },
                      {
                        // symbol:
                        //   "path://M13.811,7h3.918L10.874,0,4.021,7H8.036c0,5-1.568,8.5-4.993,11C7.937,17,12.833,14,13.811,7Z",
                        coord: [item[0], 0],
                        value: `${value2}℃`,
                        label: {
                          position: "top",
                          color: chart.color
                        },
                        itemStyle: {
                          color: chart.color
                        }
                      }
                    ]
                  }
                });
                flg = flg1;
              }
            });
            series.push({
              name: "2#测量温度",
              type: "line",
              // smooth: false,
              data: list,
              connectNulls: false,
              // min: 0,
              // max: 594,
              itemStyle: {
                normal: {
                  color: chart.color
                }
              }
            });
            series = series.concat(dashedLine);
          });
          const option = {
            background: "#fff",
            //用formatter回调函数显示多项数据内容
            tooltip: {
              trigger: "axis",
              show: true,
              formatter(params) {
                return `
            <div>${params[0].data[0]}</div>
            <div>测量温度:  ${params[0].data[2]}℃</div>
            `;
              }
            },
            legend: {
              // data: ["1#测量温度", "2#测量温度"],
              show: false
            },
            grid: {
              left: "3%",
              right: "3%",
              bottom: "3%",
              top: "7%",
              containLabel: true
            },

            xAxis: [
              {
                type: "category",
                boundaryGap: false,
                splitLine: {
                  //Y轴 分割横线
                  lineStyle: {
                    color: "#000"
                  }
                },

                axisTick: {
                  show: false,
                  lineStyle: {
                    color: "#000"
                  }
                },
                axisLabel: {
                  // color: "#e8e7e7",
                  color: "#000",
                  fontSize: 12
                }
              },
              {
                type: "value",
                show: true,
                min: 0,
                max: 100,
                splitNumber: 2,
                axisLabel: {
                  show: false
                },
                axisTick: {
                  show: false,
                  lineStyle: {
                    color: "#000"
                  }
                },
                position: "bottom",
                minorTick: {
                  show: false
                },
                splitLine: {
                  //Y轴 分割横线
                  show: true,
                  lineStyle: {
                    color: "#000"
                  }
                },
                minorSplitLine: {
                  // 细 分割横线
                  show: true,
                  lineStyle: {
                    color: "#000"
                  }
                }
              }
            ],
            yAxis: {
              min: 0,
              max: 100,
              splitNumber: 20,
              axisLabel: {
                lineStyle: {
                  color: "#000"
                }
              },
              splitLine: {
                //Y轴 分割横线
                show: true,
                alignWithLabel: true,
                lineStyle: {
                  width: 1,
                  color: "#000"
                }
              },
              axisLine: {
                //Y轴 轴线
                show: false,
                lineStyle: {
                  color: "#000"
                }
              },
              axisTick: {
                show: false
                // lineStyle: {
                //   color: "#ffffff",
                // },
              },
              // minorTick: {
              //   show: true,
              // },
              minorSplitLine: {
                // 细 分割横线
                show: true,
                lineStyle: {
                  color: "#000"
                }
              }
            },

            series: series
          };
          console.log("option :>> ", option);
          echart.lineChart.setOption(option);
        });
      });
    },

    // 弹窗打开执行操作
    handleOpen() {},
    close() {
      this.$refs.originalChart.disposeChart();
      this.$emit("update:visible", false);
    }
  }
};
</script>
<style lang="scss">
html {
  height: auto !important;
}
</style>
<style media="print">
@page {
  size: auto;
  margin: 0mm;
}

/* html {
  background-color: #ffffff;
  height: auto;
  margin: 0px;
} */

body {
  /* border: solid 1px #ffffff; */
  /* margin: 10mm 15mm 10mm 15mm; */
}
@page {
  size: A4;
}
/* 隐藏打印预览的页眉和页脚 */
@page {
  size: auto; /* auto is the initial value */
  margin: 0mm; /* this affects the margin in the printer settings */
}
</style>
